# -*- coding: UTF-8 -*-
# @author:Claire
# @time: 2021/03/03
# @file : DingTalk.py

import json
import urllib.request
import time
import hmac
import hashlib
import base64
import urllib.parse

def DingTalk(ding_url, secret, content_text, atMobiles):
    timestamp = str(round(time.time() * 1000))
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    send_url = "%s&timestamp=%s&sign=%s" % (ding_url, timestamp, sign)

    header = {
        "Content-Type": "application/json",
        "Charset": "UTF-8"
    }

    # 3、构建请求数据
    data = {
        "msgtype": "text",
        "text": {
            "content": content_text

        },
        "at": {
            "atMobiles": [
                atMobiles
            ],
            "isAtAll": False     #@全体成员（在此可设置@特定某人）
        }
    }

    #4、对请求的数据进行json封装
    sendData = json.dumps(data)#将字典类型数据转化为json格式
    sendData = sendData.encode("utf-8") # python3的Request要求data为byte类型
    #5、发送请求
    request = urllib.request.Request(url=send_url, data=sendData, headers=header)
    #6、将请求发回的数据构建成为文件格式
    opener = urllib.request.urlopen(request)
    return opener